﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using GamePlugin.Logics.Core;

namespace GamePlugin.Logics.Data
{
    public class SearchInfoItemList : DependencyObject
    {
        public SearchInfoItemList()
        {
            Children = new ObservableCollection<SearchItem>();
        }

        public static readonly DependencyProperty ChildrenProperty =
            DependencyProperty.Register("Children", typeof(ObservableCollection<SearchItem>), typeof(SearchInfoItemList), null);
        [Editable]
        public ObservableCollection<SearchItem> Children
        {
            get { return (ObservableCollection<SearchItem>)GetValue(ChildrenProperty); }
            set { SetValue(ChildrenProperty, value); }
        }

        public void SelectItemUp()
        {
            int current = Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex;
            if (current < 1)
                return;
            int exchange = current - 1;

            var temp = Children[current];
            Children[current] = Children[exchange];
            Children[exchange] = temp;

            Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex = exchange;
        }

        public void SelectItemDown()
        {
            int current = Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex;
            if (current >= Children.Count - 1)
                return;
            int exchange = current + 1;

            var temp = Children[current];
            Children[current] = Children[exchange];
            Children[exchange] = temp;

            Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex = exchange;
        }

        public void Sort()
        {
            int current = Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex;

            SearchItem[] list = Children.ToArray<SearchItem>();
            for (int i = 0; i < list.Length; i++)
                for (int j = i + 1; j < list.Length; j++)
                    if (list[i].SearchInfoName.CompareTo(list[j].SearchInfoName) < 0)
                    {
                        var temp = list[i];
                        list[i] = list[j];
                        list[j] = temp;

                        if (i == current) { current = j; continue; }
                        if (j == current) { current = i; continue; }
                    }
            Children.Clear();
            for (int i = 0; i < list.Length; i++)
                Children.Add(list[i]);
            if (current >= 0)
                Helper.GetMainWindow().searchInfoList.searchListBox.SelectedIndex = current;
        }
    }
}
